import json
from django.http import JsonResponse, FileResponse, HttpResponse
from App.models import *
from bigdata.settings import *
import hashlib
from django.utils import timezone as datetime
from django.utils.encoding import escape_uri_path
from django.core.paginator import Paginator
from django.db import transaction
import logging

collect = logging.getLogger('django')


def login(request):
    if request.method == 'POST':
        print("用户正在登陆")
        data = json.loads(request.body)

        user = data['user']
        password = data['password']

        user_info = User.objects.filter(user_name=user)
        if len(user_info) == 0:
            msg = {
                'msg': '登录失败!',
                'team': {},
                'captain': {},
                'teacher': {},
                'member': []
            }
            req = JsonResponse(msg, charset='utf8')
            return req

        if len(user_info) > 1 or ' ' in user or ' ' in password:
            msg = {
                'msg': '登录失败!',
                'team': {},
                'captain': {},
                'teacher': {},
                'member': []
            }
            req = JsonResponse(msg, charset='utf8')
            return req

        user_info = user_info.first()
        password = hashlib.md5(bytes('{}'.format(password).encode(encoding='UTF-8'))).hexdigest()
        if str(password) != str(user_info.pass_word):
            msg = {
                'msg': '登录失败!',
                'team': {},
                'captain': {},
                'teacher': {},
                'member': []
            }
            req = JsonResponse(msg, charset='utf8')
            return req

        if user_info:
            try:
                varify = "D2TA654KIO3M380-D.*@DKH23NC55611*"
                if data["varify"] == varify:
                    if TeamData.objects.filter(user_index__user_name=user).exists():
                        result = {
                            "msg": "登录成功!",
                            "user": data['user'],
                            "code": 200,
                            "type": 101 if TeamData.objects.get(user_index__user_name=user).track == 0 else 102
                        }
                        return JsonResponse(result, charset='utf8')
            except:
                pass
            if user_info.info:
                t = TeamData.objects.get(user_index=user_info)
                p = PeopleData.objects.filter(team_index=t)

                t_number = t.teams_number
                t_name = t.teams_name
                t_time = t.submit_time.strftime('%Y-%m-%d %H:%M:%S')
                t_id = t.team_id

                member = []
                teacher = {}
                captain = {}
                for n in p:
                    if n.is_captain == 1:
                        captain = {
                            'school': n.people_school, 'name': n.people_name, 'sex': n.get_people_sex_display(),
                            'email': n.people_email, 'card_id': n.id_card_id, 'stu_card_id': n.stu_id_card_id,
                            'type': '队长', 'student_number': n.student_number, 'id_number': n.id_number,
                            'iphone_number': n.iphone_number, 'major': n.major, 'nationality': n.nationality,
                            'nationality_type': n.nationality_type
                        }
                    elif n.is_captain == 2:
                        teacher = {
                            'school': n.people_school, 'name': n.people_name, 'sex': n.get_people_sex_display(),
                            'email': n.people_email, 'type': '指导老师', 'iphone_number': n.iphone_number
                        }
                    else:
                        temp = {'school': n.people_school, 'name': n.people_name, 'sex': n.get_people_sex_display(),
                                'email': n.people_email, 'card_id': n.id_card_id, 'stu_card_id': n.stu_id_card_id,
                                'type': '队员', 'student_number': n.student_number, 'id_number': n.id_number,
                                'iphone_number': n.iphone_number, 'major': n.major, 'nationality': n.nationality,
                                'nationality_type': n.nationality_type
                                }

                        member.append(temp)
                if user_info.examine_info != 2:
                    msg = {
                        'msg': '登录成功!',
                        'examine': {
                            'status': user_info.get_examine_info_display(),
                            'msg': user_info.examine_msg,
                            'time': user_info.examine_time.strftime('%Y-%m-%d %H:%M:%S')
                        },
                        'team': {
                            'id': t_id,
                            'number': t_number,
                            'name': t_name,
                            'time': t_time
                        },
                        'captain': captain,
                        'teacher': teacher,
                        'member': member
                    }
                else:
                    msg = {
                        'msg': '登录成功!',
                        'examine': {
                            'status': user_info.get_examine_info_display(),
                            'msg': user_info.examine_msg,
                            'time': ''
                        },
                        'team': {
                            'id': t_id,
                            'number': t_number,
                            'name': t_name,
                            'time': t_time
                        },
                        'captain': captain,
                        'teacher': teacher,
                        'member': member
                    }
            else:
                msg = {
                    'msg': '登录成功!',
                    'examine': {},
                    'team': {},
                    'captain': {},
                    'teacher': {},
                    'member': []
                }
            req = JsonResponse(msg, charset='utf8')
            req.set_cookie('user', user, 60 * 30)

            return req
        else:
            msg = {
                'msg': '没有该用户或账号密码错误!'
            }
            return JsonResponse(msg, charset='utf8')


def register(request):
    if request.method == 'POST':
        data = json.loads(request.body)

        user = data['user']
        password = data['password']
        user_info = User.objects.filter(user_name=user)

        if user_info:
            msg = {
                'msg': '注册失败,已存在用户!'
            }
            return JsonResponse(msg, charset='utf8')
        else:
            print("正在测试注册接口")
            password = hashlib.md5(bytes('{}'.format(password).encode(encoding='UTF-8'))).hexdigest()
            u = User(user_name=user, pass_word=password)
            u.save()
            msg = {
                'msg': '注册成功!'
            }
            return JsonResponse(msg, charset='utf8')


def join(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            user_name = data['user']
            team_name = data['title']
            team_number = data['number']
            team_track = int(data['track'])

            captain_name = data['captain']['name']
            captain_sex = data['captain']['sex']
            captain_email = data['captain']['email']
            captain_school = data['captain']['school']
            captain_card = data['captain']['card_id']
            stu_captain_card = data['captain']['stu_card_id']
            captain_number = data['captain']['student_number']
            captain_id_number = data['captain']['id_number']
            captain_iphone_number = data['captain']['iphone_number']
            captain_major = data['captain']['major']

            captain_nationality = data['captain']['nationality']
            captain_nationality_type = data['captain']['nationality_type']

            teacher_name = data['teacher']['name']
            teacher_sex = data['teacher']['sex']
            teacher_email = data['teacher']['email']
            teacher_school = data['teacher']['school']
            teacher_number = data['teacher']['iphone_number']


            print(data)
            if team_number == '1':
                try:
                    with transaction.atomic():
                        u = User.objects.get(user_name=user_name)
                        if u.info:
                            msg = {
                                'msg': '已有报名信息!'
                            }
                        else:
                            t = TeamData(teams_name=team_name, teams_number=team_number, user_index=u, track=team_track)
                            t.save()

                            sex_dict = {'男': 0, '女': 1}
                            caption = PeopleData(people_school=captain_school, people_name=captain_name,
                                                 people_sex=sex_dict[captain_sex],
                                                 people_email=captain_email, is_captain=1, team_index=t,
                                                 id_card_id=captain_card,
                                                 stu_id_card_id=stu_captain_card, student_number=captain_number,
                                                 id_number=captain_id_number, iphone_number=captain_iphone_number,
                                                 major=captain_major, nationality_type=captain_nationality_type,
                                                 nationality=captain_nationality)

                            teacher = PeopleData(people_school=teacher_school, people_name=teacher_name,
                                                 people_sex=sex_dict[teacher_sex],
                                                 people_email=teacher_email, is_captain=2, team_index=t,
                                                 iphone_number=teacher_number)

                            caption.save()
                            teacher.save()

                            cap_lim = PeopleData.objects.filter(id_number=captain_id_number)
                            if len(cap_lim) > 1:
                                raise Exception('Error')

                            u.info = 1
                            u.save()

                            msg = {
                                'msg': '报名成功!'
                            }
                        return JsonResponse(msg, charset='utf8')
                except Exception as e:
                    collect.error(e)
                    msg = {
                        'msg': '报名失败,已有队长/队员报名,请检查!'
                    }
                    return JsonResponse(msg, charset='utf8')
            else:
                try:
                    with transaction.atomic():
                        u = User.objects.get(user_name=user_name)
                        if u.info:
                            msg = {
                                'msg': '已有报名信息!'
                            }
                        else:
                            t = TeamData(teams_name=team_name, teams_number=team_number, user_index=u, track=team_track)
                            t.save()

                            sex_dict = {'男': 0, '女': 1}
                            caption = PeopleData(people_school=captain_school, people_name=captain_name,
                                                 people_sex=sex_dict[captain_sex],
                                                 people_email=captain_email, is_captain=1, team_index=t,
                                                 id_card_id=captain_card,
                                                 stu_id_card_id=stu_captain_card, student_number=captain_number,
                                                 id_number=captain_id_number, iphone_number=captain_iphone_number,
                                                 major=captain_major, nationality_type=captain_nationality_type,
                                                 nationality=captain_nationality)

                            teacher = PeopleData(people_school=teacher_school, people_name=teacher_name,
                                                 people_sex=sex_dict[teacher_sex],
                                                 people_email=teacher_email, is_captain=2, team_index=t,
                                                 iphone_number=teacher_number)

                            caption.save()
                            teacher.save()
                            for i in data['member']:
                                m = PeopleData(people_school=i['school'], people_name=i['name'],
                                               people_sex=sex_dict[i['sex']],
                                               people_email=i['email'], team_index=t, id_card_id=i['card_id'],
                                               stu_id_card_id=i['stu_card_id'], student_number=i['student_number'],
                                               id_number=i['id_number'], iphone_number=i['iphone_number'],
                                               major=i['major'],
                                               nationality_type=i['nationality_type'],
                                               nationality=i['nationality'])
                                m.save()
                            cap_lim = PeopleData.objects.filter(id_number=captain_id_number)
                            if len(cap_lim) > 1:
                                raise Exception('Error')

                            for i in data['member']:
                                lim = PeopleData.objects.filter(id_number=i['id_number'])
                                if len(lim) > 1:
                                    raise Exception('Error')
                            u.info = 1
                            u.save()

                            msg = {
                                'msg': '报名成功!'
                            }
                        return JsonResponse(msg, charset='utf8')
                except Exception as e:
                    collect.error(e)
                    msg = {
                        'msg': '报名失败,已有队长/队员报名, 请重新检查!'
                    }
                    return JsonResponse(msg, charset='utf8')
        except:
            msg = {
                'msg': '报名失败,请重新检查!'
            }
            return JsonResponse(msg, charset='utf8')


def info(request):
    if request.method == 'GET':
        user = request.GET.get('user')
        try:
            user_info = User.objects.get(user_name=user)

            if user_info.info:
                t = TeamData.objects.get(user_index=user_info)
                p = PeopleData.objects.filter(team_index=t)

                t_number = t.teams_number
                t_name = t.teams_name
                t_time = t.submit_time.strftime('%Y-%m-%d %H:%M:%S')
                t_id = t.team_id

                member = []
                teacher = {}
                captain = {}
                for n in p:
                    if n.is_captain == 1:
                        captain = {
                            'school': n.people_school, 'name': n.people_name, 'sex': n.get_people_sex_display(),
                            'email': n.people_email, 'card_id': 0, 'stu_card_id': 0,
                            'type': '队长', 'student_number': n.student_number, 'id_number': n.id_number,
                            'iphone_number': n.iphone_number, 'major': n.major, 'nationality': n.nationality,
                            'nationality_type': n.nationality_type
                        }
                    elif n.is_captain == 2:
                        teacher = {
                            'school': n.people_school, 'name': n.people_name, 'sex': n.get_people_sex_display(),
                            'email': n.people_email, 'type': '指导老师', 'iphone_number': n.iphone_number
                        }
                    else:
                        temp = {'school': n.people_school, 'name': n.people_name, 'sex': n.get_people_sex_display(),
                                'email': n.people_email, 'card_id': 0, 'stu_card_id': 0,
                                'type': '队员', 'student_number': n.student_number, 'id_number': n.id_number,
                                'iphone_number': n.iphone_number, 'major': n.major, 'nationality': n.nationality,
                                'nationality_type': n.nationality_type
                                }

                        member.append(temp)
                if user_info.examine_info != 2:
                    msg = {
                        'status': 1,
                        'examine': {
                            'status': user_info.get_examine_info_display(),
                            'msg': user_info.examine_msg,
                            'time': user_info.examine_time.strftime('%Y-%m-%d %H:%M:%S')
                        },
                        'team': {
                            'id': t_id,
                            'number': t_number,
                            'name': t_name,
                            'time': t_time
                        },
                        'captain': captain,
                        'teacher': teacher,
                        'member': member
                    }
                else:
                    msg = {
                        'status': 1,
                        'examine': {
                            'status': user_info.get_examine_info_display(),
                            'msg': user_info.examine_msg,
                            'time': ''
                        },
                        'team': {
                            'id': t_id,
                            'number': t_number,
                            'name': t_name,
                            'time': t_time
                        },
                        'captain': captain,
                        'teacher': teacher,
                        'member': member
                    }
            else:
                msg = {
                    'status': 0,
                    'team': {},
                    'examine': {},
                    'captain': {},
                    'teacher': {},
                    'member': []
                }
        except:
            msg = {
                'status': 0,
                'team': {},
                'examine': {},
                'captain': {},
                'teacher': {},
                'member': []
            }
        return JsonResponse(msg, charset='utf8')


def rejoin(request):
    if request.method == 'POST':
        data = json.loads(request.body)

        user_name = data['user']
        team_name = data['title']
        team_number = int(data['number'])

        captain_name = data['captain']['name']
        captain_sex = data['captain']['sex']
        captain_email = data['captain']['email']
        captain_school = data['captain']['school']
        captain_card = data['captain']['card_id']
        stu_captain_card = data['captain']['stu_card_id']
        captain_number = data['captain']['student_number']
        captain_id_number = data['captain']['id_number']
        captain_iphone_number = data['captain']['iphone_number']
        captain_major = data['captain']['major']
        captain_nationality = data['captain']['nationality']
        captain_nationality_type = data['captain']['nationality_type']

        teacher_name = data['teacher']['name']
        teacher_sex = data['teacher']['sex']
        teacher_email = data['teacher']['email']
        teacher_school = data['teacher']['school']
        teacher_number = data['teacher']['iphone_number']

        try:
            with transaction.atomic():
                u = User.objects.get(user_name=user_name)
                t = TeamData.objects.get(user_index=u)
                sex_dict = {'男': 0, '女': 1}

                u.examine_info = 2
                u.save()

                if team_number == t.teams_number:
                    t.teams_name = team_name
                    t.submit_time = datetime.now()
                    t.save()

                    caption = PeopleData.objects.get(is_captain=1, team_index=t)
                    caption.people_school = captain_school
                    caption.people_name = captain_name
                    caption.people_sex = sex_dict[captain_sex]
                    caption.people_email = captain_email
                    caption.id_card_id = captain_card
                    caption.stu_id_card_id = stu_captain_card

                    caption.student_number = captain_number
                    caption.id_number = captain_id_number
                    caption.iphone_number = captain_iphone_number
                    caption.major = captain_major
                    caption.nationality_type = captain_nationality_type
                    caption.nationality = captain_nationality

                    teacher = PeopleData.objects.get(is_captain=2, team_index=t)
                    teacher.people_school = teacher_school
                    teacher.people_name = teacher_name
                    teacher.people_sex = sex_dict[teacher_sex]
                    teacher.people_email = teacher_email
                    teacher.iphone_number = teacher_number

                    caption.save()
                    teacher.save()

                    m = PeopleData.objects.filter(team_index=t, is_captain=0)
                    for g, i in enumerate(data['member']):
                        temp = m[g]
                        temp.people_school = i['school']
                        temp.people_name = i['name']
                        temp.people_sex = sex_dict[i['sex']]
                        temp.people_email = i['email']
                        temp.id_card_id = i['card_id']
                        temp.stu_id_card_id = i['stu_card_id']

                        temp.student_number = i['student_number']
                        temp.id_number = i['id_number']
                        temp.iphone_number = i['iphone_number']
                        temp.major = i['major']
                        temp.nationality = i['nationality']
                        temp.nationality_type = i['nationality_type']

                        temp.save()
                    for i in data['member']:
                        lim = PeopleData.objects.filter(id_number=i['id_number'])
                        if len(lim) > 1:
                            raise Exception('Error')

                    cap_lim = PeopleData.objects.filter(id_number=captain_id_number)
                    if len(cap_lim) > 1:
                        raise Exception('Error')

                elif team_number > t.teams_number:
                    t.teams_name = team_name
                    t.teams_number = team_number
                    t.submit_time = datetime.now()
                    t.save()

                    caption = PeopleData.objects.get(is_captain=1, team_index=t)
                    caption.people_school = captain_school
                    caption.people_name = captain_name
                    caption.people_sex = sex_dict[captain_sex]
                    caption.people_email = captain_email
                    caption.id_card_id = captain_card
                    caption.stu_id_card_id = captain_card

                    caption.student_number = captain_number
                    caption.id_number = captain_id_number
                    caption.iphone_number = captain_iphone_number
                    caption.major = captain_major
                    caption.nationality_type = captain_nationality_type
                    caption.nationality = captain_nationality

                    teacher = PeopleData.objects.get(is_captain=2, team_index=t)
                    teacher.people_school = teacher_school
                    teacher.people_name = teacher_name
                    teacher.people_sex = sex_dict[teacher_sex]
                    teacher.people_email = teacher_email
                    teacher.iphone_number = teacher_number

                    caption.save()
                    teacher.save()

                    m = PeopleData.objects.filter(team_index=t, is_captain=0)
                    for g, i in enumerate(data['member']):
                        try:
                            temp = m[g]
                            temp.people_school = i['school']
                            temp.people_name = i['name']
                            temp.people_sex = sex_dict[i['sex']]
                            temp.people_email = i['email']
                            temp.id_card_id = i['card_id']
                            temp.stu_id_card_id = i['stu_card_id']

                            temp.student_number = i['student_number']
                            temp.id_number = i['id_number']
                            temp.iphone_number = i['iphone_number']
                            temp.major = i['major']
                            temp.nationality = i['nationality']
                            temp.nationality_type = i['nationality_type']

                            temp.save()
                        except:
                            temp = PeopleData(people_school=i['school'], people_name=i['name'],
                                              people_sex=sex_dict[i['sex']],
                                              people_email=i['email'], team_index=t, id_card_id=i['card_id'],
                                              student_number=i['student_number'], id_number=i['id_number'],
                                              iphone_number=i['iphone_number'], nationality=i['nationality'],
                                              nationality_type=i['nationality_type'])
                            temp.save()

                    cap_lim = PeopleData.objects.filter(id_number=captain_id_number)
                    if len(cap_lim) > 1:
                        raise Exception('Error')

                    for i in data['member']:
                        lim = PeopleData.objects.filter(id_number=i['id_number'])
                        if len(lim) > 1:
                            raise Exception('Error')
                elif team_number < t.teams_number:
                    t.teams_name = team_name
                    t.teams_number = team_number
                    t.submit_time = datetime.now()
                    t.save()

                    caption = PeopleData.objects.get(is_captain=1, team_index=t)
                    caption.people_school = captain_school
                    caption.people_name = captain_name
                    caption.people_sex = sex_dict[captain_sex]
                    caption.people_email = captain_email
                    caption.id_card_id = captain_card
                    caption.stu_id_card_id = stu_captain_card

                    caption.student_number = captain_number
                    caption.id_number = captain_id_number
                    caption.iphone_number = captain_iphone_number
                    caption.major = captain_major
                    caption.nationality_type = captain_nationality_type
                    caption.nationality = captain_nationality

                    teacher = PeopleData.objects.get(is_captain=2, team_index=t)
                    teacher.people_school = teacher_school
                    teacher.people_name = teacher_name
                    teacher.people_sex = sex_dict[teacher_sex]
                    teacher.people_email = teacher_email
                    teacher.iphone_number = teacher_number

                    caption.save()
                    teacher.save()

                    m = PeopleData.objects.filter(team_index=t, is_captain=0)
                    for g, i in enumerate(m):
                        try:
                            temp = data['member'][g]
                            i.people_school = temp['school']
                            i.people_name = temp['name']
                            i.people_sex = sex_dict[temp['sex']]
                            i.people_email = temp['email']
                            i.id_card_id = temp['card_id']
                            i.stu_id_card_id = temp['stu_card_id']

                            i.student_number = temp['student_number']
                            i.id_number = temp['id_number']
                            i.iphone_number = temp['iphone_number']
                            i.major = temp['major']
                            i.nationality = temp['nationality']
                            i.nationality_type = temp['nationality_type']

                            i.save()
                        except:
                            i.delete()

                    cap_lim = PeopleData.objects.filter(id_number=captain_id_number)
                    if len(cap_lim) > 1:
                        raise Exception('Error')

                    for i in data['member']:
                        lim = PeopleData.objects.filter(id_number=i['id_number'])
                        if len(lim) > 1:
                            raise Exception('Error')
            msg = {
                'msg': '报名成功!'
            }
        except Exception as e:
            collect.error(e)
            msg = {
                'msg': '报名失败,已有队长/队员报名!'
            }
        return JsonResponse(msg, charset='utf8')


def getfile(request):
    if request.method == 'GET':
        filename = request.GET.get('filename')
        try:
            f = open(os.path.join(NOTICE_URL, filename), 'rb')
            response = FileResponse(f)
            response['content_type'] = "application/octet-stream;charset=utf-8"
            return response
        except:
            return HttpResponse('ERROR')


def upload_img(request):
    print("正在上传图片")
    if request.method == 'POST':
        id_file = request.FILES.get('file', None)
        if not id_file:
            msg = {
                'msg': '上传失败!',
                'id': 'None'
            }
            return JsonResponse(msg, charset='utf8')

        file_id = IdCard()

        file_id.save()

        file_id_md5 = hashlib.md5(bytes('{}'.format(file_id.card_id).encode(encoding='UTF-8'))).hexdigest()

        file_id.file_id = file_id_md5

        file_id.save()

        img_md5 = file_id_md5 + ".jpg"

        md5_path = os.path.join(IMG_URL, str(img_md5))

        if not os.path.exists(md5_path):
            fp = open(md5_path, 'wb+')
            for chunk in id_file.chunks():
                fp.write(chunk)
            fp.close()

        msg = {
            'msg': '上传成功!',
            'id': file_id.card_id
        }
        return JsonResponse(msg, charset='utf8')


def get_all_file(request):
    if request.method == 'GET':
        msg = {
            'filename': [escape_uri_path(i) for i in os.listdir(NOTICE_URL)]
        }
        return JsonResponse(msg, charset='utf8')


def get_img(request):
    if request.method == 'GET':
        img_id = request.GET.get('img')
        print(img_id)
        try:
            img_name = IdCard.objects.get(card_id=img_id).file_id
            print(img_name)
            f = open(os.path.join(IMG_URL, img_name + '.jpg'), 'rb')
            response = FileResponse(f)
            response['content_type'] = "application/octet-stream;charset=utf-8"
            return response
        except:
            return HttpResponse('ERROR')


def get_stu_img(request):
    if request.method == 'GET':
        img_id = request.GET.get('img')
        try:
            img_name = StudentIdCard.objects.get(student_card_id=img_id).student_file_id
            f = open(os.path.join(STUDENT_IMG_URL, img_name + '.jpg'), 'rb')
            response = FileResponse(f)
            response['content_type'] = "application/octet-stream;charset=utf-8"
            return response
        except:
            return HttpResponse('ERROR')


def upload_stu_img(request):
    print("正在上传学生证")
    if request.method == 'POST':
        id_file = request.FILES.get('file', None)
        if not id_file:
            msg = {
                'msg': '上传失败!',
                'id': 'None'
            }
            return JsonResponse(msg, charset='utf8')

        student_file_id = StudentIdCard()

        student_file_id.save()

        student_file_id_md5 = hashlib.md5(
            bytes('{}'.format(student_file_id.student_card_id).encode(encoding='UTF-8'))).hexdigest()

        student_file_id.student_file_id = student_file_id_md5

        student_file_id.save()

        student_img_md5 = student_file_id_md5 + ".jpg"

        md5_path_ = os.path.join(STUDENT_IMG_URL, str(student_img_md5))

        if not os.path.exists(md5_path_):
            fp = open(md5_path_, 'wb+')
            for chunk in id_file.chunks():
                fp.write(chunk)
            fp.close()
        msg = {
            'msg': '上传成功!',
            'id': student_file_id.student_card_id
        }
        return JsonResponse(msg, charset='utf8')


def get_all_info(request):
    if request.method == 'GET':
        pages = int(request.GET.get('pages'))
        all_user = TeamData.objects.all().order_by('team_id')
        all_user_ = Paginator(all_user, 20)
        data = []
        try:
            for i in all_user_.page(pages):
                u = i.user_index
                p = PeopleData.objects.filter(team_index=i)

                t_number = i.teams_number
                t_name = i.teams_name
                t_time = i.submit_time.strftime('%Y-%m-%d %H:%M:%S')
                t_track = "高职高专本科" if i.track == 0 else "研究生"

                member = []
                teacher = {}
                captain = {}
                for n in p:
                    if n.is_captain == 1:
                        captain = {
                            'school': n.people_school, 'name': n.people_name, 'sex': n.get_people_sex_display(),
                            'email': n.people_email, 'card_id': n.id_card_id, 'stu_card_id': n.stu_id_card_id,
                            'type': '队长', 'student_number': n.student_number, 'id_number': n.id_number,
                            'iphone_number': n.iphone_number, 'major': n.major, 'nationality': n.nationality,
                            'nationality_type': n.nationality_type
                        }
                    elif n.is_captain == 2:
                        teacher = {
                            'school': n.people_school, 'name': n.people_name, 'sex': n.get_people_sex_display(),
                            'email': n.people_email, 'type': '指导老师', 'iphone_number': n.iphone_number
                        }
                    else:
                        temp_ = {'school': n.people_school, 'name': n.people_name,
                                 'sex': n.get_people_sex_display(),
                                 'email': n.people_email, 'card_id': n.id_card_id, 'stu_card_id': n.stu_id_card_id,
                                 'type': '队员', 'student_number': n.student_number, 'id_number': n.id_number,
                                 'iphone_number': n.iphone_number, 'major': n.major, 'nationality': n.nationality,
                                 'nationality_type': n.nationality_type
                                 }

                        member.append(temp_)

                if u.examine_info != 2:
                    data.append(
                        {'id': i.team_id,
                         'status': u.get_examine_info_display(),
                         'time': u.examine_time.strftime('%Y-%m-%d %H:%M:%S'),
                         'team': {
                             'number': t_number,
                             'name': t_name,
                             'time': t_time,
                             'track': t_track
                         },
                         'captain': captain,
                         'teacher': teacher,
                         'member': member
                         })
                else:
                    data.append(
                        {'id': i.team_id,
                         'status': u.get_examine_info_display(),
                         'time': '',
                         'team': {
                             'number': t_number,
                             'name': t_name,
                             'time': t_time,
                             'track': t_track
                         },
                         'captain': captain,
                         'teacher': teacher,
                         'member': member
                         })

            msg = {
                'msg': '获取成功!',
                'max_number': all_user_.num_pages,
                'info': data,
            }
            return JsonResponse(msg, charset='utf8')
        except Exception as e:
            collect.error(e)
            msg = {
                'msg': 'page无效!',
                'info': []
            }
            return JsonResponse(msg, charset='utf8')


def examine(request):
    if request.method == 'POST':
        data = json.loads(request.body)

        team_id = data['id']
        msg = data['msg']
        status = data['status']
        try:
            with transaction.atomic():
                user_info = TeamData.objects.get(team_id=team_id).user_index
                user_info.examine_msg = msg
                user_info.examine_time = datetime.now()
                user_info.examine_info = status
                user_info.save()

                if user_info.info:
                    msg = {
                        'msg': '审核成功!',
                    }
                    return JsonResponse(msg, charset='utf8')
                else:
                    msg = {
                        'msg': '队伍还没报名!',
                    }
                    return JsonResponse(msg, charset='utf8')
        except:
            msg = {
                'msg': 'id无效!',
            }
            return JsonResponse(msg, charset='utf8')


def reset(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        user = data['user']
        password = data['password']

        try:
            with transaction.atomic():
                user_info = User.objects.get(user_name=user)
                password = hashlib.md5(bytes('{}'.format(password).encode(encoding='UTF-8'))).hexdigest()
                user_info.pass_word = password
                user_info.save()

                msg = {
                    'msg': '修改成功!',
                }
                return JsonResponse(msg, charset='utf8')
        except:
            msg = {
                'msg': '没有该用户!',
            }
            return JsonResponse(msg, charset='utf8')
